<template>
  <div id="chat-page"
       :style="{
  width:'100%',
  minHeight: (this.getWinSize().height-135)+'px',
  paddingTop:(this.getSafeArea().top+40)+'px'
  }">
    <div class="shadow-box"></div>
    <div class="page-title" :style="{
      top:(this.getSafeArea().top)+'px'
    }">
      <div id="back-button" @click="$router.push('ChatList')">
        <i href="javascript:void(0)" class="el-icon-arrow-left"></i>
      </div>
      <div class="title" style="width: 80%">
        <img :src="currChatSession.fromIcon">
        <span v-text="currChatSession.fromMainName"></span>
        <el-tag type="success" v-text="dict.UserTypeMap[currChatSession.fromUserType]"></el-tag>
      </div>
      <span class="complaint-button" @click="contactSystemUser" v-if="currChatSession.fromUserType!=='SysUser'">
        举报
      </span>
    </div>

    <div v-if="currChatSession.id>0" id="content-wapper"
         v-loading="isLoading"
         element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.5)"
         :style="{
    }">
      <div id="content" :style="{
    }">
        <div class="item" v-for="(item,index) in messageList">
          <div class="time" v-if="item.timeInfo">
            <span> {{ item.timeInfo }} </span>
          </div>
          <template v-if="item.fromUserType!=='Member'">
            <div class="item-content shop">
              <div class="icon">
                <div class="img" :style="{backgroundImage:'url('+item.fromUserIcon+')'}"></div>
                <span class="name" v-text="item.fromUserName"></span>
              </div>
              <div class="message" @click="setCurrId(item.id)" :class="{curr:item.id===currId}" :style="{
                maxWidth:messageWidth
              }">
                <div class="text" v-html="showMessage(item)"></div>
                <!--                <textarea class="text" v-model="item.message" v-if="item.messageType==='text'"></textarea>-->
                <!--                <div class="time" v-text="item.createdTime.substring(5)"></div>-->
                <i class="el-icon-error" @click="deleteMessage(index,item)"></i>
              </div>
              <div class="c"></div>
              <!--              <div class="report">-->
              <!--                <span v-if="!item.isReport" @click="reportMessage(index)">举报</span>-->
              <!--                <span class="reported" v-if="item.isReport">已举报</span>-->
              <!--              </div>-->
            </div>
          </template>

          <template v-if="item.fromUserType==='Member'">
            <div class="item-content me">
              <div class="icon">
                <div class="img" :style="{backgroundImage:'url('+currUser.icon+')'}"></div>
                <!--                <span class="name">我</span>-->
              </div>
              <div class="message" @click="setCurrId(item.id)" :class="{curr:item.id===currId}" :style="{
                maxWidth:messageWidth
              }">
                <div class="text" v-html="showMessage(item)"></div>
                <!--                <textarea class="text message-text" v-model="item.message" v-if="item.messageType.id==='text'" :style="{-->
                <!--                  width:(((item.message.length)*9).toFixed(0))+'px',-->
                <!--                maxWidth:'80%'-->
                <!--              }"></textarea>-->
                <i class="el-icon-error" @click="deleteMessage(index,item)"></i>
              </div>
              <div class="c"></div>
            </div>
          </template>
        </div>
        <div class="c"></div>
      </div>
    </div>

    <div id="bottom-box">
      <div class="image-upload-box" @click="chooseImageVideo">
        <i class="el-icon-picture" style="font-size: 28px; position: relative; left: 5px; top: 5px;"/>
<!--        <el-upload-->
<!--          name="myUploadFile"-->
<!--          :action="UploadFileUrl"-->
<!--          :headers="getHeader()"-->
<!--          accept="image/png, image/jpeg, image/jpg, image/gif, video/mp4, video/quicktime"-->
<!--          :show-file-list="false"-->
<!--          :on-success="successUpload"-->
<!--          :before-upload="checkUploadFile">-->
<!--          <i class="el-icon-picture upload-icon"></i>-->
<!--        </el-upload>-->

      </div>
      <!--      <div class="icon-box">-->
      <!--        <emotion-box/>-->
      <!--        <i class="iconfont icon-biaoqing"></i>-->
      <!--      </div>-->
      <div class="input-box">
        <el-input :maxlength="500" size="small" v-model="sendMessageContent"></el-input>
      </div>
      <div class="submit-box">
        <el-button type="danger" @click="sendTextMessage" v-if="!sendMessageTextButtonLoading">发送</el-button>
        <el-button type="danger" v-if="sendMessageTextButtonLoading" disabled>发送中</el-button>
      </div>
    </div>

    <my-photo ref="my-photo"/>
  </div>
</template>

<script>
import 'viewerjs/dist/viewer.css'
import Viewer from 'viewerjs'
import MyPhoto from "../common/MyPhoto";

export default {
  name: 'Chat',
  components: {MyPhoto},
  data: function () {
    return {
      currId: 0,
      pageSize: 20,
      messageWidth: (this.getWinSize().width - 110) + 'px',
      maxMessageId: false,
      minMessageId: false,
      sendMessageContent: '',
      currUser: {
        nickname: '',
        icon: this.NoImageUrl,
        sex: '',
      },
      // currShop: {
      //   id: 13,
      //   logo: 'http://image.yangfankj.com/shop/logo/13.jpg',
      //   name: '每一天便利店',
      // },
      currChatSession: {
        'id': 0,
        'userId': 22,
        'userType': 'Member',
        'fromId': 7,
        'fromUserType': 'Shop',
        'fromIcon': this.NoImageUrl,
        'fromName': '',
        'fromClerkId': 52,
        'lastMessage': '在吗，刚才在忙。',
        'unReadNums': 0,
        'lastMessageTime': '2022-08-30 04:08:43'
      },
      // messageList:demoData.chatList,
      messageList: [],
      messageTotal: 0,
      myGallery: false,
      myIscroll: false,
      isLoading: false,
      sendMessageTextButtonLoading: false,
      demoList: [10, 11]
    }
  },
  mounted() {
    let $this = this
    setTimeout(function () {
      $this.getUserInfo()
    }, 1200)
    // 获取参数中店铺信息
    $this.getChatSessionDetail(function () {
      // 获取最新消息(10条)
      $this.getNewMessageList('new')
      window.onscroll = function () {
        let scrollPos = $this.getScrollTop()
        if (scrollPos === 0) {
          // 到达顶部
          $this.getNewMessageList('before')
        }
        // console.log('scrollPos', scrollPos)
      }
    })

    $this.bus.$on('NewSocketMessage', function (data) {
      // 判断当前消息,是否为当前会话
      if (data.userId === $this.currChatSession.fromUserId) {
        $this.getNewMessageList('after')
      }
    })
  },
  destroyed() {
    this.bus.$off('NewSocketMessage')
    window.onscroll = null
  },
  methods: {
    chooseImageVideo:function () {
      let $this = this
      $this.$refs['my-photo'].chooseAct(function(filePath){
        $this.uploadAndParseFile(filePath,function (response) {
          if (response.code>0){
            return $this.$message.error('上传文件失败: '+response.message)
          }else{
            $this.sendMessage(response.data, 'image')
          }
        })
      },'all')
    },
    setCurrId: function (id) {
      if (id === this.currId) {
        this.currId = 0
      } else {
        this.currId = id
      }
      this.$forceUpdate()
    },
    contactSystemUser: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Member/checkAndGetMessageSession', {
        userType: 'SysUser',
        mainId: 0
      }, function (data) {
        if (data && data.id) {
          $this.$router.push({
            name: 'Chat',
            query: {
              chatSessionId: data.id
            }
          })
          location.reload()
        }
        $this.$forceUpdate()
      }, function (msg) {
        $this.$message.error(msg)
        // $this.form.password = ''
      })
    },
    deleteMessage: function (index, messageItem) {
      let $this = this
      $this.$confirm('您确认要进行该操作吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        $this.isLoading = true
        $this.MyRequest($this.ApiDoNameMember + 'Member/chatSendMessageDelete', {
          id: messageItem.id,
        }, function (data) {
          $this.isLoading = false
          $this.messageList.splice(index, 1)
          $this.checkTime()
          $this.$forceUpdate()
        }, function (data) {
          $this.isLoading = false
          $this.$forceUpdate()
          $this.successTip(data.message, 'error')
        })
      }).catch(() => {

      });
    },
    checkTime: function () {
      let $this = this
      $this.messageList.forEach(function (value, index) {
        if (index === 0) {
          $this.$set($this.messageList[index], 'timeInfo', value.createdTime.substring(0, 16))
          // value.timeInfo=value.createdTime.substring(0,12)
        } else {
          var beforeDate = Date.parse($this.messageList[index - 1].createdTime) / 1000
          var date = Date.parse(value.createdTime) / 1000
          var diff = date - beforeDate
          if (diff > 300) {
            $this.$set($this.messageList[index], 'timeInfo', value.createdTime.substring(0, 16))
          }
        }
      })
    },
    getUserInfo: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Member/info', {}, function (data) {
        $this.currUser.icon = data.icon
        $this.currUser.nickname = data.nickname
        $this.currUser.sex = data.sex
        $this.$forceUpdate()
      }, function (data) {
        $this.$forceUpdate()
        $this.successTip(data.message, 'error')
      })
    },
    // 获取聊天会话信息
    getChatSessionDetail: function (callback) {
      var url = 'Member/chatMessageSessionDetail'
      var params = {}
      // 1.从会话列表进入
      if (this.$route.query.chatSessionId) {
        params = {chatSessionId: this.$route.query.chatSessionId}
      }

      // 2.从店铺名称点击进入
      if (this.$route.query.shopId) {
        url = 'Member/checkAndGetMessageSession'
        params = {mainId: this.$route.query.shopId}
      }

      let $this = this
      $this.isLoading = true
      $this.MyRequest($this.ApiDoNameMember + url, params, function (data) {
        $this.isLoading = false
        $this.currChatSession = data
        callback()
        $this.$forceUpdate()
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.successTip(data.message, 'error')
      })
    },
    /**
     * 拉取消息
     * @param type
     */
    getNewMessageList: function (type) {
      let $this = this
      $this.isLoading = true
      var requestParams = {
        chatSessionId: $this.currChatSession.id,
        sortProp: 'id',
        sortOrder: 'ASC',
        pageSize: this.pageSize
      }
      if (type === 'new') {
        // requestParams.sortOrder="DESC"
        requestParams.sortOrder = 'DESC'
        console.log('拉取最新')
      }
      if (type === 'before' && this.minMessageId) {
        requestParams.sortOrder = 'DESC'
        requestParams.minMessageId = this.minMessageId
        console.log('拉取当前之前')
      }
      if (type === 'after' && this.maxMessageId) {
        requestParams.maxMessageId = this.maxMessageId
        console.log('拉取当前之后')
      }
      $this.MyRequest($this.ApiDoNameMember + 'Member/chatMessageList', requestParams, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        if (type === 'new' || type === 'before') {
          data.list = data.list.reverse()
        }
        if (data.list.length === 0) {
          return
        }
        $this.setMessageList(data.list, type)
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.successTip(data.message, 'error')
      })
    },
    /**
     * 设置消息
     * @param messageList
     * @param type
     */
    setMessageList: function (messageList, type) {
      let $this = this
      switch (type) {
        // 创建新消息
        case 'new':
          $this.messageList = messageList
          break
        // 获取历史
        case 'before':
          $this.messageList = messageList.concat($this.messageList)
          break
        // 获取新的
        case 'after':
          $this.messageList = $this.messageList.concat(messageList)
          break
      }
      // 1.当条数大于20条,才有可能还有未加载的消息
      if ($this.messageList.length >= 0) {
        $this.minMessageId = $this.messageList[0].id
      }
      $this.maxMessageId = $this.messageList[$this.messageList.length - 1].id
      $this.$forceUpdate()
      if (type === 'after' || type === 'new') {
        setTimeout(function () {
          window.scrollTo(0, 99999)
        }, 500)
      }
      // 设置图片消息查看
      $this.handlerImageShow()
      $this.checkTime()
    },
    // 显示消息
    showMessage: function (messageItem) {
      let $this = this
      if (messageItem.messageType.id === 'image') {
        return '<img class="image-message" style="max-width: 100px" src="' + messageItem.message + '" />'
      } else if (messageItem.messageType.id === 'video') {
        return '<div class="video-message"><div _src="' + messageItem.message + '" onclick="playVideo(this)" class="shadow-box"></div>' +
          '<i class="el-icon-video-play" _src="' + messageItem.message + '"  onclick="playVideo(this)"></i>' +
          '<img src="' + messageItem.message + '?x-oss-process=video/snapshot,t_0,f_jpg" width="180" style="max-width: 180px" alt=""/>' +
          '</div>'
      } else if (messageItem.messageType.id === 'ShopProduct') {
        return '<div class="message-product">' +
          '<div class="message-product-image"><img src="' + messageItem.fileInfo.image + '"></div>' +
          '<div class="message-product-name ovd_s">' + messageItem.fileInfo.shopProductName + '</div>' +
          '<div class="message-product-model ovd_s">型号: ' + messageItem.fileInfo.model + '</div>' +
          '<div class="message-product-price"><span>￥' + $this.ToMoney(messageItem.fileInfo.price) + '</span> <button onclick="showProductDetail(' + messageItem.fileInfo.shopProductId + ',\'' + messageItem.fileInfo.model + '\')">查看商品详情</button></div></div>'
      } else {
        return messageItem.message
      }
    },
    checkUploadFile: function (file) {
      var fileArr = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'video/mp4', 'video/quicktime']
      if (fileArr.indexOf(file.type) === -1) {
        this.$message.error('只允许上传: ' + fileArr.join(',') + ' 类型文件')
        return false
      }
      return true
    },
    // 上传成功
    successUpload: function (response, file) {
      let $this = this
      console.log('file', file)
      if (response.code === 0) {
        $this.sendMessage(response.data, 'image')
      } else {
        this.successTip('聊天上传图片失败: ' + response.message, 'error')
      }
    },
    // 发送消息
    sendMessage: function (message, messageType) {
      let $this = this
      $this.isLoading = true
      if (messageType === 'text') {
        $this.sendMessageTextButtonLoading = true
      }
      $this.MyRequest($this.ApiDoNameMember + 'Member/chatSendMessage', {
        chatSessionId: $this.currChatSession.id,
        toUserType: $this.currChatSession.fromUserType,
        platform: "H5",
        message: message,
        messageType: messageType,
      }, function (data) {
        $this.isLoading = false
        $this.sendMessageTextButtonLoading = false
        $this.$forceUpdate()
        if (messageType === 'text') {
          $this.sendMessageContent = ''
        }
        $this.getNewMessageList('after')
      }, function (data) {
        $this.isLoading = false
        $this.$forceUpdate()
        $this.successTip(data.message, 'error')
      })
    },
    sendTextMessage: function () {
      this.sendMessage(this.sendMessageContent, 'text')
    },
    handlerImageShow: function () {
      let $this = this
      if ($this.myGallery) {
        $this.myGallery.destroy()
      }
      setTimeout(function () {
        $this.myGallery = new Viewer(document.getElementById('content-wapper'))
      }, 500)
    },
    iscrollHandler: function () {
      /*       let $this=this
            this.myIscroll = new IScroll(this.$refs.content, {
              mouseWheel: true,
              scrollbars: true,
              // 解决拖拽卡顿问题
              scrollX: false,
              scrollY: true,
              disablePointer: true,
              disableTouch: false,
              disableMouse: true
            })

            this.myIscroll.on('scrollEnd', function () {
              var height = this.y,
                bottomHeight = this.maxScrollY - height;
              // 控制下拉显示
              if (Math.abs(height) > 60) {
                // isPulled = true;
                console.log('上拉恢复')

              } else if (height === 0) {
                $this.addBeforeMessage()
                console.log('上拉到底')
              }

              // 控制上拉显示
              if (Math.abs(bottomHeight) > 60) {
                console.log('下拉恢复')
                // isPulled = true;
              } else if (bottomHeight === 0) {
                // pullUp.style.display = "none";
                console.log('下拉到底')
              }
            }) */
    }
  }
}
</script>

<style scoped>
.complaint-button {
  font-size: 13px;
  position: absolute;
  right: 10px;
  top: -8px;
  text-decoration: underline
}
</style>
